<?php

namespace App\Admin\Controllers;

use App\Models\Material;
use App\Models\MaterialClassify;
use App\Models\Supplier;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Arr;

class MaterialController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '原材料';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Material());

        $grid->column('classify.title', '原料分类');
        $grid->column('suppliers.company', '供应商');
        $grid->column('name', __('Name'));
        $grid->column('id', __('Stock'))->mystock();
        $grid->column('number', '编号');
        $grid->column('created_at', __('Created at'))->sortable();

        $grid->actions(function ($actions) {
            $actions->disableView();
        });

        $grid->filter(function ($filter) {
            $filter->disableIdFilter();

            $filter->equal('material_classify_id', '分类')
                ->select(Arr::except(MaterialClassify::selectOptions(), '0'));
            $filter->equal('supplier_id', '供应商')
                ->select(Supplier::where('status', 1)->pluck('company', 'id'));
        });
        $grid->disableActions();
        $grid->disableCreateButton();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Material::findOrFail($id));

        $show->field('material_classify_id', '原料分类')
            ->as(function ($value){
                $value = MaterialClassify::where('id', $value)->get('title');
                return $value[0]->title;
            });
        $show->field('supplier_id', '供应商')
            ->as(function ($value) {
                $value = Supplier::where('id', $value)->get('company');
                return $value[0]->company;
            });
        $show->field('name', __('Name'));
        $show->field('stock', __('Stock'));
        $show->field('number', __('Number'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Material());

        $form->select('material_classify_id', '材料分类')
            ->options(Arr::except(MaterialClassify::selectOptions(), '0'))
            ->required();

        $form->select('supplier_id' ,'供应商')
            ->options(Supplier::where('status', 1)->pluck('company', 'id'))
            ->required();
        $form->text('name', __('Name'))->required();
        $form->number('stock', __('Stock'))->default('0')->required();
        $form->hidden('number', '材料编号');

        return $form;
    }
}
